/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);
    }
    window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStore = name => {
    if (!name) return;
    var value = window.localStorage.getItem(name);
    if (value !== null) {
        try {
            value = JSON.parse(value);
        } catch (e) {
            value = value;
        }
    }
    return value;
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
    if (!name) return;
    window.localStorage.removeItem(name);
}

/**
 * 让整数自动保留2位小数
 */
// export const returnFloat = value => { 
//     var value=Math.round(parseFloat(value)*100)/100; 
//     var xsd=value.toString().split("."); 
//     if(xsd.length==1){ 
//         value=value.toString()+".00"; 
//         return value;   
//     } 
//     if(xsd.length>1){ 
//         if(xsd[1].length<2){ 
//             value=value.toString()+"0"; 
//         } 
//         return value; 
//     } 
// } 
/**
 * @param {date} 标准时间格式:Fri Nov 17 2017 09:26:23 GMT+0800 (中国标准时间)
 * @param {type} 类型
 *   type == 1 ---> "yyyy-mm-dd hh:MM:ss.fff"
 *   type == 2 ---> "yyyymmddhhMMss"
 *   type == '' ---> "yyyy-mm-dd hh:MM:ss"
 */
export const formatDate = (date, type) => {
    var year = date.getFullYear();//年
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;//月
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();//日
    var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();//时
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();//分
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();//秒
    var milliseconds = date.getMilliseconds() < 10 ? "0" + date.getMilliseconds() : date.getMilliseconds() //毫秒
    if (type == 1) {
        return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds + "." + milliseconds;
    } else if (type == 2) {
        return year + "" + month + "" + day + "" + hour + "" + minutes + "" + seconds;
    } else if (type == 3) {
        return year + "-" + month + "-" + day;
    } else {
        return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
    }
}
/**
 * 时间转换：20150101010101 --> '2015-01-01 01:01:01'
 */
export const parseToDate = (timeValue) => {
    var result = "";
    var year = timeValue.substr(0, 4);
    var month = timeValue.substr(4, 2);
    var date = timeValue.substr(6, 2);
    var hour = timeValue.substr(8, 2);
    var minute = timeValue.substr(10, 2);
    var second = timeValue.substr(12, 2);
    result = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    return result;
}
/**
 * 判断空值
 */
export const isEmpty = (keys) => {
    if (typeof keys === "string") {
        keys = keys.replace(/\"|&nbsp;|\\/g, '').replace(/(^\s*)|(\s*$)/g, "");
        if (keys == "" || keys == null || keys == "null" || keys === "undefined") {
            return true;
        } else {
            return false;
        }
    } else if (typeof keys === "undefined") {  // 未定义
        return true;
    } else if (typeof keys === "number") {
        return false;
    } else if (typeof keys === "boolean") {
        return false;
    } else if (typeof keys == "object") {
        if (JSON.stringify(keys) == "{}") {
            return true;
        } else if (keys == null) { // null
            return true;
        } else {
            return false;
        }
    }

    if (keys instanceof Array && keys.length == 0) {// 数组
        return true;
    }

}

/**
 * 返回两位的小数的字符串
 */
export const toFixedNum = (num) => {
    const tonum = Number(num).toFixed(2);
    return tonum;
}

export const showMessage = () => {
    this.$message({
        showClose: true,
        message: '对不起，您暂无此操作权限~',
        type: 'success'
    });
}

/**
 * 读取base64
 */
export const readFile = file => {
    //var file = this.files[0];
    //判断是否是图片类型
    if (!/image\/\w+/.test(file.raw.type)) {
        alert("只能选择图片");
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        var filedata = {
            filename: file.name,
            filebase64: e.target.result
        }
        alert(e.target.result)
    }
}

/**
 * 动态插入css
 */
export const loadStyle = url => {
    const link = document.createElement('link')
    link.type = 'text/css'
    link.rel = 'stylesheet'
    link.href = url
    const head = document.getElementsByTagName('head')[0]
    head.appendChild(link)
}
/**
 * 设置浏览器头部标题
 */
export const setTitle = (title) => {
    title = title ? `${title}` : '渡石'
    window.document.title = title
}

export const param2Obj = url => {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}
export const obj2Param = (obj) => {

    return Object.keys(obj)
        .map((key) => key + "=" + obj[key])
        .join("&");
};

//是否为正整数
export const isInteger = (s) => {
    var re = /^[0-9]+$/;
    return re.test(s)
}

export const setContentHeight = (that, ele, height) => {
    that.$nextTick(() => {
        ele.style.height = (document.body.clientHeight - height) + 'px'
    })
}
/**
 * 时间戳转化为10位的字符串
 */
export const timestamp10 = (time) => {
    if (time) {
        return String(time).substring(0, 10)
    }
}
/**
 * 转化成分
 * @param {*} num 
 * @param {*} isNumber 不传返回字符串，传true返回数字
 * @returns 
 */
export const parseFen = (num, isNumber = false) => {
    if (num) {
        return isNumber ? num * 1 : num * 1 + '';
    }
}
export const parseYuan = (num, isNumber = false) => {
    if (num) {
        return isNumber ? num / 1 : num / 1 + '';
    }
}
export const downloadFile = (fileName, filePath) => {
    let link = document.createElement('a');
    filePath = filePath.replace("http:", "https:");
    let url = filePath;
    // 这里是将url转成blob地址，
    fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
        link.href = URL.createObjectURL(blob);
        // console.log(link.href);
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
    });
}
//input输入框限制只能输入两位小数
export const filterTwoNumber = (value) => {
    value = value
        // .replace(/[^\d.]/g, "") //将非数字和点以外的字符替换成空
        // .replace(/^\./g, "") //验证第一个字符是数字而不是点
        .replace(/\.{2,}/g, ".") //出现多个点时只保留第一个
        .replace(".", "$#$") // 1、将数字的点替换成复杂字符$#$
        .replace(/\./g, "") // 2、将字符串的点直接清掉
        .replace("$#$", ".") // 3、将复杂字符再转换回点-
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
    // if (value.indexOf(".") < 0 && value != "") {
    //     value = parseFloat(value);
    // } else if (value.indexOf(".") > 1 && value[0] === '0') {
    //     value = parseFloat(value);
    // }
    return value.toString()
}
//input输入框限制只能输入三位小数
export const filterThreeNumber = (value) => {
    value = value
        .replace(/[^\d.]/g, "") //将非数字和点以外的字符替换成空
        .replace(/^\./g, "") //验证第一个字符是数字而不是点
        .replace(/\.{2,}/g, ".") //出现多个点时只保留第一个
        .replace(".", "$#$") // 1、将数字的点替换成复杂字符$#$
        .replace(/\./g, "") // 2、将字符串的点直接清掉
        .replace("$#$", ".") // 3、将复杂字符再转换回点
        .replace(/^(\-)*(\d+)\.(\d\d\d).*$/, "$1$2.$3"); //只能输入三个小数
    if (value.indexOf(".") < 0 && value != "") {
        value = parseFloat(value);
    } else if (value.indexOf(".") > 1 && value[0] === '0') {
        value = parseFloat(value);
    }
    return value.toString()
}


//获取父级id
export const getParentIds = (id, data) => {
    function backtrack(data, id, parents) {
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            // (1)找到id则返回父级id
            if (item.id === id) return parents;
            // (2)判断是否要递归
            if (!item.next_level_data || !item.next_level_data.length) continue;
            // (3)递归前当前id入栈
            parents.push(item.id);
            //(4)如果递归找到id，则返回父级id
            if (backtrack(item.next_level_data, id, parents).length) return parents;
            // (5)如果递归没找到，当前id出栈
            parents.pop();
        }
        return [];
    }
    return backtrack(data, id, []);
}
export const commonAdd = (number1, number2) => {
    if (Number.isNaN(number1)) {
        number1 = 0
    }
    if (Number.isNaN(number2)) {
        number2 = 0
    }
    let result = 0;
    if (Number.isInteger(number1) && Number.isInteger(number2)) {
        result = number1 + number2;
    } else {
        //两个都是纯小数
        const number1Array = (number1).toString().split('.');
        const number2Array = (number2).toString().split('.');
        //最大的除数位数
        let maxBit = 1;
        let n1Decimals = (number1Array[1] || '').length;
        let n2Decimals = (number2Array[1] || '').length;
        if (n1Decimals >= n2Decimals) {
            maxBit = n1Decimals + 1;
        } else {
            maxBit = n2Decimals + 1;
        }
        const divisor = parseInt('1'.padEnd(maxBit, 0));
        result = (parseInt(number1 * divisor) + parseInt(number2 * divisor)) / divisor;
    }
    return result;
}
export const commonAddMulty = (...args) => {
    const argSum = args || []
    let sum = 0;
    sum = argSum.reduce((prev, next) => {
        next = next || 0
        return commonAdd(prev, next * 1);
    }, 0);
    return sum;
};
/**
 * 
 * @param {*} bindValue name
 * @returns true-有权限
 */
export const isHavePermission = (bindValue) => {
    let user = JSON.parse(localStorage.getItem("user") || "{}");
    let btnPermissionsArr = user.button_name_list;
    let isShow;
    if (btnPermissionsArr) {
        // 传入数组-数组都没有权限不展示
        if (bindValue instanceof Array) {
            isShow = bindValue.some((item) =>
                btnPermissionsArr.includes(item)
            );
            // 传入字符串
        } else {
            if (bindValue === '') {
                isShow = true
                return isShow;
            }
            isShow = btnPermissionsArr.includes(bindValue);
        }
        //   // console.log(bindValue, isShow ? "展示" : "隐藏", "button===>permission");
        return isShow;
    }
}
export const URL_API = () => {
    let url_origin = ""
    if (window.location.origin == "http://demo.tms.dushisc.com") {
        url_origin = process.env.VUE_APP_TEST
    } else if (window.location.origin == "https://tms.dushisc.com") {
        url_origin = process.env.VUE_APP_DEV
    } else if (window.location.origin == "http://dev.tms.dushisc.com") {
        url_origin = process.env.VUE_APP_TOOL
    } else if (window.location.origin == "http://dev.tms.dushisc.com:7777") {
        url_origin = process.env.VUE_APP_VERSION7
    }
    else if (window.location.origin == "http://dev.tms.dushisc.com:7776") {
        url_origin = process.env.VUE_APP_VERSION6
    }
    else if (window.location.origin == "http://dev.tms.dushisc.com:7775") {
        url_origin = process.env.VUE_APP_VERSION5
    }
    else if (window.location.origin == "http://dev.tms.dushisc.com:7774") {
        url_origin = process.env.VUE_APP_VERSION4
    }
    else if (window.location.origin == "http://dev.tms.dushisc.com:7773") {
        url_origin = process.env.VUE_APP_VERSION3
    }
    else if (window.location.origin == "http://dev.tms.dushisc.com:7772") {
        url_origin = process.env.VUE_APP_VERSION2
    }
    else if (window.location.origin == "http://dev.tms.dushisc.com:7771") {
        url_origin = process.env.VUE_APP_VERSION1
    }
    else {
        url_origin = process.env.VUE_APP_LOCAL
        // url_origin = "http://192.168.3.148:8080"
    }
    return url_origin
}